package com.desheng.bigdata.flink.common;

import java.util.Arrays;

public class ByteUtil {
    public static byte[] int2Bytes(int i) {
        byte[] result = new byte[4];
        result[0] = (byte)((i >> 24) & 0xFF);
        result[1] = (byte)((i >> 16) & 0xFF);
        result[2] = (byte)((i >> 8) & 0xFF);
        result[3] = (byte)(i & 0xFF);
        return result;
    }
    /**
     * byte[]转int
     * @param bytes 需要转换成int的数组
     * @return int值
     */
    public static int bytes2Int(byte[] bytes) {
        int value=0;
        for(int i = 0; i < bytes.length; i++) {
            int shift= (bytes.length - i - 1) * 8;
            value +=(bytes[i] & 0xFF) << shift;
        }
        return value;
    }

    public static int byte2Int(byte b) {
        byte[] bytes = new byte[4];
        bytes[0] = 0;
        bytes[1] = 0;
        bytes[2] = 0;
        bytes[3] = b;
        return bytes2Int(bytes);
    }

    public static byte[] subArray(byte[] array, int start, int len) {

        if(start < 0 || start > array.length || (start + len) > array.length) {
            throw new ArrayIndexOutOfBoundsException("数组越界");
        }
        byte[] result = new byte[len];
        for(int i = start; i < start + len; i++) {
            result[i - start] = array[i];
        }
        return result;
    }

    public static void main(String[] args) {
        byte[] bytes = int2Bytes(13);
        System.out.println(Arrays.toString(bytes));
        System.out.println("bytes2Int: " + bytes2Int(bytes));
        System.out.println("宋建华".getBytes().length);
        System.out.println(byte2Int((byte)3));

//        bytes = new byte[2];
//        bytes[0] = 13;
//        bytes[1] = 6;
//        int i = bytes2Int(bytes);
//        System.out.println("bytes2Int: " + i);
//        System.out.println(Arrays.toString(int2Bytes(i)));

        System.out.println("------------------------");
        byte[] subBytes = subArray(bytes, 1, 3);
        System.out.println(Arrays.toString(subBytes));
    }
}
